<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>socket.io</title>
  <style>
    body {
      font-size: 14px;
    }

    #root {
      width: 500px;
      height: 300px;
      overflow-y: auto;
      border: 1px solid #ccc;
    }
  </style>
</head>

<body>
  <div id="root"></div>

  <div>
    <input type="text" oninput="setMsg(this)" id="msg" onkeyup="onEnter(event)">
    <button onclick="send()">发送数据</button>
  </div>

  <!-- 引用socket.io客户端脚本程序 -->
  <script src="/socket.io/socket.io.js"></script>
  <script>
    let msg = ''
    let name = ''
    name = prompt('您的姓名是什么?')

    let client = io('/')

    client.on('open', () => {
      client.emit('name', name)
    })


    client.on('message', data => {
      appendRootDom(data)
    })

    function appendRootDom(data) {
      let div = document.createElement('div')
      div.style.cssText = 'color:blue;'
      let toUserHtml = `<span onclick="toUser('${data.username}')">【${data.username}】</span>`
      if (data.username.startsWith('【我】')) {
        div.style.cssText = 'color:green;'
        toUserHtml = `<span>${data.username}</span>`
      }
      div.innerHTML = toUserHtml + data.msg + ' -- ' + data.at
      document.querySelector('#root').appendChild(div)
      document.querySelector('#root').scrollTop = document.querySelector('#root').scrollHeight
    }

    function toUser(username) {
      let to = '@' + username + ' '
      document.getElementById('msg').value = to
      document.getElementById('msg').focus()
    }

    function onEnter(evt) {
      evt = window.event || evt
      // evt.keyCode == 13
      if (evt.key == "Enter") {
        send()
      }
    }

    function setMsg(obj) {
      msg = obj.value
    }
    // 发送数据
    function send() {
      // send它是一个语法糖 client.emit('message','内容')
      client.send(msg)
      msg = ''
      document.getElementById('msg').value = msg
    }

  </script>

</body>

</html>